package ch.bfh.android.WhereAmI;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import ch.simplix.android.net.discoverer.bluetooth.BluetoothDiscovererService;
import ch.simplix.android.net.discoverer.bluetooth.BluetoothMeasurement;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver {
	private static final String LogCategory = "WhereAmI.SmsReceiver";
	//
	private byte[] passwordHash = { 25, -75, -123, 67, -56, 91, -105, -59, 73,
			-114, -33, -40, -100, 17, -61, -86, -116, -75, -2, 81 };

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			// ---get the SMS message passed in---
			Bundle bundle = intent.getExtras();
			SmsMessage[] msgs = null;

			if (bundle != null) {
				// ---retrieve the SMS message received---
				Object[] pdus = (Object[]) bundle.get("pdus");

				msgs = new SmsMessage[pdus.length];

				for (int i = 0; i < msgs.length; i++) {
					msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
					String message = msgs[i].getMessageBody().toString();
					try {
						byte[] messageHash = createHash(message);
						if (Arrays.equals(messageHash, passwordHash)) {
							Intent locationIntent = new Intent("ch.bfh.android.WhereAmI.LOCATION_SERVICE");
							locationIntent.putExtra(LocationService.EXTRA_DISCOVER, true);
							locationIntent.putExtra(LocationService.EXTRA_SENDER, msgs[i].getOriginatingAddress());
							context.startService(locationIntent);
						}

					} catch (NoSuchAlgorithmException e) {
						Log.d(LogCategory, "error hashing sms", e);
					} catch (UnsupportedEncodingException e) {
						Log.d(LogCategory, "error encoding sms", e);
					}
				}
			}
		} catch (Exception e) {
			Log.d(LogCategory, "error receiving sms", e);
		}

	}

	private byte[] createHash(String text) throws NoSuchAlgorithmException,
			UnsupportedEncodingException {
		MessageDigest md;
		md = MessageDigest.getInstance("SHA-1");
		byte[] sha1hash = new byte[40];
		md.update(text.getBytes(), 0, text.length());
		sha1hash = md.digest();
		return sha1hash;
	}
}
